package com.zhilehuo.pretask.adapter

import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestListener
import com.zhilehuo.pretask.R
import com.zhilehuo.pretask.databinding.ItemPageBinding
import com.zhilehuo.pretask.poko.PageContent
import com.bumptech.glide.request.target.Target
import com.zhilehuo.pretask.ui.article.ArticleFragment
import com.zhilehuo.pretask.ui.article.ArticleViewModel
import timber.log.Timber

/**
 * @Description: 读一读页面适配器
 * @Author: Realnt
 * @Date:
 */
class ArticlePagerAdapter(private val fragment: ArticleFragment, private val viewModel: ArticleViewModel) : RecyclerView.Adapter<ArticlePagerAdapter.PageViewHolder>() {
    private val items = mutableListOf<PageContent>()

    var onPageChangeListener: ((Int) -> Unit)? = null // 页面更改回调

    /**
     * @Description: 单页内部类
     * @Author: Realnt
     * @Date:
     */
    inner class PageViewHolder(val binding: ItemPageBinding) : RecyclerView.ViewHolder(binding.root){
        val ivImage = binding.ivPageImage
        val tvErrMsg = binding.tvErrMsg
        val tvContent = binding.tvContent
        fun bind() {
            binding.apply {
                setupControls()
            }
        }

        /**
         * @Description: 初始化按钮控制
         * @Param  :
         * @Return  :
         */
        private fun setupControls() {
            binding.btnPlay.setOnClickListener { fragment.togglePlayPause() }
            binding.btnReplay.setOnClickListener { fragment.replayCurrentPage() }
            binding.btnVolume.setOnClickListener { fragment.adjustVolume() }
        }
    }

    /**
     * @Description: 提交更改
     * @Param newItems : 页面内容
     * @Return  :
     */
    fun submitList(newItems: List<PageContent>) {
        items.clear()
        items.addAll(newItems)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PageViewHolder {
        LayoutInflater.from(parent.context)
            .inflate(R.layout.item_page, parent, false)
        return PageViewHolder(ItemPageBinding.inflate(LayoutInflater.from(parent.context), parent, false))
    }

    override fun onBindViewHolder(holder: PageViewHolder, position: Int) {
        val item = items[position]

        /* 关键一步, Android 系统默认禁止了明文 HTTP 流量（即不使用 HTTPS 的 HTTP 请求）, 能改直接改, 不能改改配置*/
        val imageUrl = item.imgUrl.replace("http://", "https://")

        Glide.with(holder.ivImage.context)
            .load(imageUrl)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .placeholder(R.drawable.linux_icon)
            .transition(DrawableTransitionOptions.withCrossFade())
            .error(R.drawable.ic_launcher_foreground)
            .listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    // 处理加载失败
                    Timber.tag("error").e(e?.message.toString())
                    e?.logRootCauses("Glide") // 打印所有根因
                    e?.printStackTrace() // 输出完整堆栈
                    e?.let {
                        // 显示错误信息
                        Toast.makeText(holder.ivImage.context, "加载失败: ${it.message}", Toast.LENGTH_SHORT).show()
                        holder.tvErrMsg.text = e.message
                    }
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable?,
                    model: Any?,
                    target: Target<Drawable>?,
                    dataSource: com.bumptech.glide.load.DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }
            })
            .into(holder.ivImage)

        holder.bind()

        /* 触发页面切换回调 */
        holder.itemView.post {
            if (holder.adapterPosition == position) return@post //标记退出
            onPageChangeListener?.invoke(holder.adapterPosition)
        }
    }

    override fun getItemCount() = items.size
}